import 'dart:collection';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/b2cpick/b2cpickfeedbackscreen.dart';
import 'package:opene/ui/b2cpick/b2cpickmodel.dart';
import 'package:toast/toast.dart';

class B2CPickSubmitScreen extends StatelessWidget {
  B2CPickBean b2cPickBean;
  PickupPol3Location pickupPol3OBLPN;

  B2CPickSubmitScreen({this.b2cPickBean, this.pickupPol3OBLPN});

  @override
  Widget build(BuildContext context) {
    return B2CPickSubmitScreenPage(b2cPickBean: b2cPickBean, pickupPol3OBLPN: pickupPol3OBLPN);
  }
}

class B2CPickSubmitScreenPage extends StatefulWidget {
  B2CPickBean b2cPickBean;
  PickupPol3Location pickupPol3OBLPN;

  B2CPickSubmitScreenPage({this.b2cPickBean, this.pickupPol3OBLPN});

  @override
  _B2CPickSubmitScreenPageState createState() => _B2CPickSubmitScreenPageState(b2cPickBean: b2cPickBean, pickupPol3Location: pickupPol3OBLPN);
}

class _B2CPickSubmitScreenPageState extends BaseState<B2CPickSubmitScreenPage> {
  B2CPickBean b2cPickBean;
  PickupPol3Location pickupPol3Location;

  _B2CPickSubmitScreenPageState({this.b2cPickBean, this.pickupPol3Location});

  final TextEditingController dateController = TextEditingController();
  final controller = ScrollController();

  int index = 0, position, ctn = 0;
  List<SkuList> data = new List();
  FocusNode ctnFocusNode = FocusNode();
  final TextEditingController ctnEditingController = TextEditingController();

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Pick: Submit";
  }

  @override
  void setFeedBack() {
    // TODO: implement setFeedBack
    super.setFeedBack();
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => B2CPickFeedbackScreen(b2cPickBean: b2cPickBean)),
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Future.delayed(Duration(milliseconds: 300), () {
      setState(() {
        feedback = true;
        data = pickupPol3Location.skuList;
      });
    });
  }

  @override
  void dispose() {
    ctnFocusNode.dispose(); // 不要忘记销毁FocusNode
    super.dispose();
  }

  @override
  Widget getViewBinding() {
    return Container(
      margin: EdgeInsets.only(left: 15, right: 15, top: 10),
      child: Column(
        children: [
          Container(
            margin: EdgeInsets.only(
              top: 0,
            ),
            child: Row(
              children: [
                Text(
                  "Pick#: ",
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                ),
                Expanded(
                  child: Text(
                    Utils.isBool(b2cPickBean.isNoneLocation) ? "NONE Location" : Utils.getStringisEmpty(b2cPickBean.pickNo),
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                  ),
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(
              top: 0,
            ),
            child: Row(
              children: [
                Text(
                  "OBLPN: ",
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                ),
                Expanded(
                  child: Text(
                    "${Utils.getStringisEmpty(b2cPickBean.oblpn)}(${b2cPickBean.inventory})",
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    // 请求焦点
                    FocusScope.of(context).requestFocus(FocusNode());
                    // setComplete();
                  },
                  child: Container(
                    padding: EdgeInsets.only(left: 5, top: 2, bottom: 2, right: 5),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: MyAppTheme.white, // 背景颜色
                      borderRadius: BorderRadius.all(Radius.circular(8.0)), // 圆角半径
                      border: Border.all(
                        color: MyAppTheme.nearlyBlue, // 边框颜色
                        width: 0.5, // 边框宽度
                      ),
                    ),
                    child: Text(
                      'Complete',
                      style: MyAppTheme.text,
                    ), // 子控件，如果需要的话
                  ),
                )
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(
              top: 0,
            ),
            child: Row(
              children: [
                Text(
                  "Location: ",
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                ),
                Expanded(
                  child: Text(
                    Utils.getStringisEmpty(pickupPol3Location.location),
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    // 请求焦点
                    FocusScope.of(context).requestFocus(FocusNode());
                    // setComplete();
                  },
                  child: Container(
                    padding: EdgeInsets.only(left: 5, top: 2, bottom: 2, right: 5),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: MyAppTheme.white, // 背景颜色
                      borderRadius: BorderRadius.all(Radius.circular(8.0)), // 圆角半径
                      border: Border.all(
                        color: MyAppTheme.nearlyBlue, // 边框颜色
                        width: 0.5, // 边框宽度
                      ),
                    ),
                    child: Text(
                      'Complete',
                      style: MyAppTheme.text,
                    ), // 子控件，如果需要的话
                  ),
                )
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(
              top: 0,
            ),
            child: Row(
              children: [
                Text(
                  "IBLPN: ",
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                ),
                Expanded(
                  child: Text(
                    Utils.getStringisEmpty(b2cPickBean.iblpn),
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    // 请求焦点
                    FocusScope.of(context).requestFocus(FocusNode());
                    // setComplete();
                  },
                  child: Container(
                    padding: EdgeInsets.only(left: 5, top: 2, bottom: 2, right: 5),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: MyAppTheme.white, // 背景颜色
                      borderRadius: BorderRadius.all(Radius.circular(8.0)), // 圆角半径
                      border: Border.all(
                        color: MyAppTheme.nearlyBlue, // 边框颜色
                        width: 0.5, // 边框宽度
                      ),
                    ),
                    child: Text(
                      'Complete',
                      style: MyAppTheme.text,
                    ), // 子控件，如果需要的话
                  ),
                )
              ],
            ),
          ),
          Container(
            margin: const EdgeInsets.only(left: 0, top: 5, right: 0, bottom: 10),
            width: double.infinity,
            child: ConstrainedBox(
              constraints: BoxConstraints(maxHeight: 35),
              child: TextField(
                controller: textEditingController,
                textInputAction: TextInputAction.search,
                onSubmitted: (String text) {
                  print('Searching for $text');
                  if (Utils.isEmpty(text)) {
                    return;
                  }
                  querySkuPutType(text);
                },
                // autofocus: true,
                decoration: InputDecoration(
                  suffixIcon: IconButton(
                    padding: EdgeInsets.all(2.0),
                    icon: Icon(
                      Icons.qr_code_scanner,
                      size: 28,
                      color: MyAppTheme.nearlyBlue,
                    ),
                    onPressed: () {
                      // requestPermissions();
                      // Utils.scanBarcode(context);
                      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                        return ScanCode();
                      })).then((text) {
                        if (text == null) {
                          return;
                        }
                        setState(() {
                          textEditingController.text = text;
                        });
                        print(text); //拿到扫描结果
                        querySkuPutType(text);
                      });
                    },
                  ),
                  border: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: MyAppTheme.nearlyBlue,
                    ),
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点之外的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点时的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  hintText: "scan inbound lpn barcode",
                  filled: true,
                  fillColor: MyAppTheme.white,
                  //隐藏下划线
                  //border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey),
                  contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                ),
                onChanged: (text) {
                  code = text;
                },
              ),
            ),
          ),
          Container(
            margin: const EdgeInsets.only(left: 15, top: 5, right: 15, bottom: 0),
            child: Row(
              children: [
                Container(
                  width: 60,
                  child: Text(
                    "Cartons: ",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                ),
                Expanded(
                  child: ConstrainedBox(
                    constraints: BoxConstraints(maxHeight: 35),
                    child: TextField(
                      maxLines: 1,
                      focusNode: ctnFocusNode,
                      controller: ctnEditingController,
                      keyboardType: TextInputType.number,
                      textInputAction: TextInputAction.next,
                      onSubmitted: (String text) {},
                      // autofocus: true,
                      decoration: InputDecoration(
                        suffixIcon: IconButton(
                          padding: EdgeInsets.all(2.0),
                          icon: Icon(
                            Icons.remove_circle_outline,
                            size: 30,
                            color: MyAppTheme.nearlyBlue,
                          ),
                          onPressed: () {
                            setState(() {
                              print("ctnonPressed");
                              if (ctn == 0) {
                                return;
                              }
                              ctn--;
                              ctnEditingController.text = "${ctn}";
                            });
                          },
                        ),
                        border: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: MyAppTheme.nearlyBlue,
                          ),
                          borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                          // 设置焦点之外的边框颜色
                          borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                          // 设置焦点时的边框颜色
                          borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                        ),
                        hintText: "Scan +1",
                        filled: true,
                        fillColor: MyAppTheme.white,
                        //隐藏下划线
                        //border: InputBorder.none,
                        hintStyle: TextStyle(color: Colors.grey),
                        contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                      ),
                      onChanged: (text) {
                        print("ctn:${text}");
                        print("code:${code}");
                        if (Utils.isEmpty(code)) {
                          ctnEditingController.text = "";
                          return;
                        }
                        if (skuUpType == null) {
                          ctnEditingController.text = "";
                          return;
                        }
                        if (Utils.isEmpty(text)) {
                          return;
                        }
                        if (text == code) {
                          ctn++;
                          ctnEditingController.text = "${ctn}";
                          Future.delayed(Duration(milliseconds: 100), () {
                            setState(() {
                              ctnFocusNode.requestFocus();
                            });
                          });
                          return;
                        }
                        if (text == "${ctn}${code}") {
                          ctn++;
                          ctnEditingController.text = "${ctn}";
                          Future.delayed(Duration(milliseconds: 100), () {
                            setState(() {
                              ctnFocusNode.requestFocus();
                            });
                          });
                          return;
                        }

                        if (!Utils.isInteger(text)) {
                          ctnEditingController.text = "${ctn}";
                          return;
                        }

                        if (int.parse(text) < 0) {
                          ctnEditingController.text = "${ctn}";
                          return;
                        } else {
                          ctn = int.parse(text);
                        }
                      },
                    ),
                  ),
                ),
              ],
            ),
          ),
          Row(
            children: [
              Text(
                "Pick# List:",
                style: MyAppTheme.text,
              ),
              Visibility(
                  visible: Utils.isBool(b2cPickBean.isNoneLocation) ? true : false,
                  child: GestureDetector(
                    onTap: () {
                      // 请求焦点
                      FocusScope.of(context).requestFocus(FocusNode());
                      // setComplete();
                    },
                    child: Container(
                      padding: EdgeInsets.only(left: 5, top: 2, bottom: 2, right: 5),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: MyAppTheme.white, // 背景颜色
                        borderRadius: BorderRadius.all(Radius.circular(8.0)), // 圆角半径
                        border: Border.all(
                          color: MyAppTheme.nearlyBlue, // 边框颜色
                          width: 0.5, // 边框宽度
                        ),
                      ),
                      child: Text(
                        'Refresh',
                        style: MyAppTheme.text,
                      ), // 子控件，如果需要的话
                    ),
                  ))
            ],
          ),
          Row(
            children: [
              Expanded(
                  flex: 1,
                  child: Text(
                    "Location",
                    style: MyAppTheme.text,
                  )),
              Expanded(
                  flex: 1,
                  child: Text(
                    "SKU(total/picked)",
                    style: MyAppTheme.text,
                  )),
            ],
          ),
          Expanded(child: setListView())
        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      shrinkWrap: true,
      // physics: NeverScrollableScrollPhysics(),
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        SkuList pol3category = data[index];
        return Column(
          children: [
            Row(
              children: [
                Expanded(
                    flex: 1,
                    child: Text(
                      Utils.isEmpty(pol3category.sku) ? "--(${pol3category.pendingQty}/${pol3category.pickedQty})" : "${pol3category.sku}(${pol3category.pendingQty}/${pol3category.pickedQty})",
                      style: MyAppTheme.test12,
                    )),
                Expanded(
                    flex: 1,
                    child: Text(
                      "${pol3category.inventoryQty}",
                      style: MyAppTheme.test12,
                    )),
              ],
            ),
            Divider(),
          ],
        );
      },
    );
  }

  @override
  void setNext() {
    ToastContext().init(context);
    if (Utils.isEmpty(textEditingController.text)) {
      Toast.show("Scan SKU/Barcode", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    if (ctn < 1) {
      Toast.show("Please input quantity", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    submitPickup();
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
    });
  }

  SkuUpType skuUpType;

  void querySkuPutType(String sku) async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }
    Map<String, dynamic> map = new HashMap();
    map["b2bJobId"] = b2cPickBean.pickNo;
    map["sku"] = sku;
    map["type"] = "B2C";

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.querySkuPutType, params: map);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      setState(() {
        skuUpType = SkuUpType.fromJson(baseResponse.data);
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void submitPickup() async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context, title: "Submit...");
    } catch (e) {
      e.toString();
    }

    PickLableQr pickLableQr = new PickLableQr();
    pickLableQr.pickup = b2cPickBean.pickNo;
    pickLableQr.lpn = b2cPickBean.iblpn;
    pickLableQr.obLpn = b2cPickBean.oblpn;
    pickLableQr.sku = textEditingController.text;
    pickLableQr.quantity = ctn;
    var json = jsonEncode(pickLableQr);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.refactorPickup, method: BaseMethod.post, data: json);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      setState(() {
        NewLabelBean newLabelBean = NewLabelBean.fromJson(baseResponse.data);
        if ((newLabelBean.pickUpLocationAndLpnRespVos != null) || (newLabelBean.pickUpLocationAndLpnRespVos.length > 0)) {
          data = newLabelBean.pickUpLocationAndLpnRespVos;
          return;
        }

        Navigator.of(context).pop(true);
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }
}
